﻿#pragma once
#ifndef ObjectPool_hpp
#define ObjectPool_hpp

#include<vector>
#include<stdexcept>
#include"../Malloc/TypesDef.hpp"
#include"../Concurrency/Lock.hpp"
#include"../Concurrency/Mutex.hpp"

namespace MMF
{
    /***
     * 使用的对象必须有无参构造函数
    */
    template<typename T>
    class ObjectPool
    {
        std::vector<T> mDatas;                  ///< 数据
        Mutex mMutex;                           ///< 互斥量
        MMFAlloc::i32 mCurIndex;                ///< 当前数据索引

    public:

        ObjectPool()
        {
            mCurIndex = 0;
        }

        ObjectPool(MMFAlloc::u32 size)
        {
            mDatas.resize(size);
            mCurIndex = 0;
        }

        ~ObjectPool()
        {

        }

        void PushObject(const T& obj)
        {
            mDatas.push_back(std::move(obj));
        }

        T& GetObject()
        {
            if (mDatas.size() == 0)
                throw std::out_of_range((__FILE__ +  std::to_string(__LINE__)).c_str());

            //加锁
            LockGuard lk(mMutex);

            mCurIndex++;
            if (mCurIndex >= mDatas.size())
                mCurIndex = 0;

            return mDatas[mCurIndex];
        }
    };
}

#endif